package com.example.springboot.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Orders;
import com.example.springboot.entity.User;
import com.example.springboot.service.OrderService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 功能: 提供接口返回数据
 * 作者: sdj
 * 日期: 2024/12/5 23:25
 */
@RestController
public class WebController {

    @Resource
    UserService userService;

    @Resource
    OrderService orderService;

    @GetMapping("/")
    public Result hello(){
        return Result.success("success");
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user){
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())){
            return Result.error("无法获取用户名或密码");
        }
        user = userService.login(user);

        //生成token
        String token = TokenUtils.createToken(user.getId().toString(), user.getPassword());
        user.setToken(token);
        return Result.success(user);
    }

    @PostMapping("/register")
    public Result register(@RequestBody User user){
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword()) || StrUtil.isBlank(user.getRole())){
            return Result.error("用户名或密码不能为空");
        }

        if(user.getUsername().length()>10 || user.getPassword().length() > 20){
            return Result.error("数据校验操失败");
        }
        user = userService.register(user);
        return Result.success(user);
    }

    @AuthAccess
    @PostMapping("/resetPassword")
    public Result resetPassword(@RequestBody User user){
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPhone())){
            return Result.error("输入信息有误");
        }
        userService.resetPassword(user);
        return Result.success();
    }

//取图表数据
    @GetMapping("/charts")
    public Result charts(){
        //取得所有数据
        List<Orders> list = orderService.list();

        //拆线图数据
        //相当于前端的list.map(item=>item.date)将list中所有的日期取出来,放到一个Set中，Set无序不可重复
        Set<String> dates = list.stream().map(Orders::getDate).collect(Collectors.toSet());
        //将无序列表转成有序列表并进行排序
        ArrayList<String> lists = CollUtil.newArrayList(dates);

        lists.sort(Comparator.naturalOrder());
        List<Dict> linList = new ArrayList<>();
        for (String date : lists) {
            //取得当天的所有金额总和，如果没有则为0
            BigDecimal sum = list.stream().filter(orders -> orders.getDate().equals(date))
                    .map(Orders::getMoney)
                    .reduce(BigDecimal::add)
                    .orElse(BigDecimal.ZERO);
            Dict dict = Dict.create();
            Dict line = dict.set("date", date).set("value", sum);
            linList.add(line);
        }

        //柱形图数据
        List<Dict> barList = new ArrayList<>();
        Set<String> dates1 = list.stream().map(Orders::getCategory).collect(Collectors.toSet());
        for (String category : dates1) {
            BigDecimal sum = list.stream().filter(orders -> orders.getCategory().equals(category))
                    .map(Orders::getMoney)
                    .reduce(BigDecimal::add)
                    .orElse(BigDecimal.ZERO);
            Dict dict = Dict.create();
            Dict bar = dict.set("name", category).set("value", sum);
            barList.add(bar);
        }
        Dict dict = Dict.create().set("line",linList).set("bar",barList);
        return Result.success(dict);
    }
}
